package com.xz.hlx11;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class LotteryActivity extends AppCompatActivity {
    private RadioGroup radioGroupFrequency;
    private RadioButton radioSingle;
    private RadioButton radioFive;
    private Button buttonStartLottery;
    private Button buttonStopLottery;
    private Button buttonRefreshHulu;
    private Button buttonClearLogin;
    private TextView textViewResult;
    private TextView textViewHuluCount;
    private EditText editTextThreshold;
    private ScrollView scrollViewResult;
    private UserData userData;
    private Handler handler;
    private Runnable lotteryRunnable;
    private boolean isLotteryRunning = false;
    private SimpleDateFormat timeFormat;
    private int currentHuluCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lottery);

        initViews();
        userData = new UserData(this);
        handler = new Handler(Looper.getMainLooper());
        timeFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault());

        // 检查用户数据
        if (!userData.hasUserData()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            startLoginActivity();
            return;
        }

        setupClickListeners();
        appendResult("应用启动成功，当前用户: " + userData.getUsername());
        
        // 首次加载时检查葫芦数量
        refreshHuluCount();
    }

    private void initViews() {
        radioGroupFrequency = findViewById(R.id.radioGroupFrequency);
        radioSingle = findViewById(R.id.radioSingle);
        radioFive = findViewById(R.id.radioFive);
        buttonStartLottery = findViewById(R.id.buttonStartLottery);
        buttonStopLottery = findViewById(R.id.buttonStopLottery);
        buttonRefreshHulu = findViewById(R.id.buttonRefreshHulu);
        buttonClearLogin = findViewById(R.id.buttonClearLogin);
        textViewResult = findViewById(R.id.textViewResult);
        textViewHuluCount = findViewById(R.id.textViewHuluCount);
        editTextThreshold = findViewById(R.id.editTextThreshold);
        scrollViewResult = findViewById(R.id.scrollViewResult);
    }

    private void setupClickListeners() {
        buttonStartLottery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startLottery();
            }
        });

        buttonStopLottery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopLottery();
            }
        });

        buttonRefreshHulu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshHuluCount();
            }
        });

        buttonClearLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearLoginInfo();
            }
        });
    }

    private void startLottery() {
        if (isLotteryRunning) {
            return;
        }

        int frequency = radioSingle.isChecked() ? 1 : 5;
        int requiredHulu = frequency * 10; // 单抽10葫芦，五连抽50葫芦
        
        // 检查葫芦数量是否充足
        if (currentHuluCount < requiredHulu) {
            appendResult("葫芦数量不足！当前: " + currentHuluCount + "，需要: " + requiredHulu);
            Toast.makeText(this, "葫芦数量不足，无法开始抽奖", Toast.LENGTH_SHORT).show();
            return;
        }

        appendResult("开始" + (frequency == 1 ? "单抽" : "五连抽") + "抽奖...");

        isLotteryRunning = true;
        updateButtonStates();

        lotteryRunnable = new Runnable() {
            @Override
            public void run() {
                if (!isLotteryRunning) {
                    return;
                }

                // 检查阈值
                int threshold = getThreshold();
                if (currentHuluCount <= threshold) {
                    appendResult("达到停止阈值(" + threshold + ")，自动停止抽奖");
                    stopLottery();
                    return;
                }

                // 检查是否有足够的葫芦进行下一次抽奖
                int requiredHulu = frequency * 10;
                if (currentHuluCount < requiredHulu) {
                    appendResult("葫芦数量不足，自动停止抽奖");
                    stopLottery();
                    return;
                }

                performSingleLottery(frequency);

                // 继续下一次抽奖，延迟1.5秒（1500ms）
                handler.postDelayed(this, 1500);
            }
        };

        handler.post(lotteryRunnable);
    }

    private void stopLottery() {
        if (!isLotteryRunning) {
            return;
        }

        isLotteryRunning = false;
        if (lotteryRunnable != null) {
            handler.removeCallbacks(lotteryRunnable);
        }
        updateButtonStates();
        appendResult("已停止抽奖");
    }

    private void performSingleLottery(int frequency) {
        int threshold = getThreshold();
        HuluxiaApi.lottery(userData.getUserId(), userData.getUserKey(), frequency, currentHuluCount, threshold, new HuluxiaApi.LotteryCallback() {
            @Override
            public void onResult(String result) {
                runOnUiThread(() -> {
                    // 扣除相应的葫芦数量
                    int usedHulu = frequency * 10;
                    currentHuluCount -= usedHulu;
                    updateHuluCountDisplay();

                    appendResult("抽奖结果: " + result + " (消耗葫芦: " + usedHulu + ")");
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    appendResult("抽奖错误: " + error);
                    // 如果是Key相关错误，停止抽奖并返回登录界面
                    if (error.contains("Key") || error.contains("登录") || error.contains("401")) {
                        stopLottery();
                        Toast.makeText(LotteryActivity.this, "登录状态失效，请重新登录", Toast.LENGTH_LONG).show();
                        userData.clearUserData();
                        startLoginActivity();
                    }
                });
            }
        });
        
    }

    private void appendResult(String text) {
        String timestamp = timeFormat.format(new Date());
        String message = "[" + timestamp + "] " + text + "\n";
        textViewResult.append(message);

        // 自动滚动ScrollView到底部
        scrollViewResult.post(() -> {
            // 使用多种方式确保滚动到底部
            scrollViewResult.fullScroll(ScrollView.FOCUS_DOWN);
            
            // 备用方案：直接滚动到TextView的底部
            scrollViewResult.postDelayed(() -> {
                int scrollY = textViewResult.getBottom() - scrollViewResult.getHeight();
                if (scrollY > 0) {
                    scrollViewResult.scrollTo(0, scrollY);
                }
            }, 100);
        });
    }

    private void updateButtonStates() {
        buttonStartLottery.setEnabled(!isLotteryRunning);
        buttonStopLottery.setEnabled(isLotteryRunning);
        buttonRefreshHulu.setEnabled(!isLotteryRunning);
        buttonClearLogin.setEnabled(!isLotteryRunning);
        radioGroupFrequency.setEnabled(!isLotteryRunning);
        radioSingle.setEnabled(!isLotteryRunning);
        radioFive.setEnabled(!isLotteryRunning);
        editTextThreshold.setEnabled(!isLotteryRunning);
    }

    private void startLoginActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopLottery();
    }

    @Override
    public void onBackPressed() {
        if (isLotteryRunning) {
            stopLottery();
        }
        super.onBackPressed();
    }

    // 刷新葫芦数量
    private void refreshHuluCount() {
        textViewHuluCount.setText("检查中...");
        buttonRefreshHulu.setEnabled(false);
        
        HuluxiaApi.checkHL(userData.getUserKey(), userData.getUserId(), new HuluxiaApi.HuluNumberCallback() {
            @Override
            public void onSuccess(int huluCount) {
                runOnUiThread(() -> {
                    currentHuluCount = huluCount;
                    updateHuluCountDisplay();
                    buttonRefreshHulu.setEnabled(!isLotteryRunning);
                    appendResult("葫芦数量更新成功: " + huluCount);
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    textViewHuluCount.setText("获取失败");
                    textViewHuluCount.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
                    buttonRefreshHulu.setEnabled(!isLotteryRunning);
                    appendResult("获取葫芦数量失败: " + error);
                    Toast.makeText(LotteryActivity.this, "获取葫芦数量失败: " + error, Toast.LENGTH_LONG).show();
                });
            }
        });
    }

    // 更新葫芦数量显示
    private void updateHuluCountDisplay() {
        textViewHuluCount.setText(String.valueOf(currentHuluCount));
        
        // 根据数量设置颜色
        int threshold = getThreshold();
        if (currentHuluCount <= threshold) {
            textViewHuluCount.setTextColor(getResources().getColor(android.R.color.holo_red_dark));
        } else if (currentHuluCount <= threshold + 50) {
            textViewHuluCount.setTextColor(getResources().getColor(android.R.color.holo_orange_dark));
        } else {
            textViewHuluCount.setTextColor(getResources().getColor(android.R.color.holo_green_dark));
        }
    }

    // 清除登录信息
    private void clearLoginInfo() {
        // 如果正在抽奖，先停止抽奖
        if (isLotteryRunning) {
            stopLottery();
        }
        
        // 显示确认对话框
        new androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("确认清除")
            .setMessage("确定要清除登录信息吗？清除后需要重新登录。")
            .setPositiveButton("确定", (dialog, which) -> {
                // 清除用户数据
                userData.clearUserData();
                appendResult("登录信息已清除");
                Toast.makeText(this, "登录信息已清除，请重新登录", Toast.LENGTH_SHORT).show();
                
                // 返回登录界面
                startLoginActivity();
            })
            .setNegativeButton("取消", null)
            .show();
    }

    // 获取设置的阈值
    private int getThreshold() {
        try {
            String thresholdText = editTextThreshold.getText().toString().trim();
            if (TextUtils.isEmpty(thresholdText)) {
                return 5000; // 默认阈值
            }
            return Integer.parseInt(thresholdText);
        } catch (NumberFormatException e) {
            return 5000; // 解析失败时使用默认值
        }
    }
}
